package com.tensquare.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author: WangYaWei
 * @description:
 * @create: 2019-08-26 09:49
 **/
@PropertySource("classpath:config/config.properties")
@Component("commonJwtUtil")
@ConfigurationProperties(prefix = "jwt.config")
public class JwtUtil {

    private String key;

    private long ttl;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public long getTtl() {
        return ttl;
    }

    public void setTtl(long ttl) {
        this.ttl = ttl;
    }

    /**
     * 生成jwt token
     * @param id
     * @param subject
     * @param roles
     * @return
     */
    public String createJwt(String id, String subject, String roles){
        long millis = System.currentTimeMillis();
        Date date = new Date(millis);
        JwtBuilder jwtBuilder = Jwts.builder()
                .setId(id)
                .setSubject(subject)
                .setIssuedAt(date)
                .signWith(SignatureAlgorithm.HS256, key)
                .claim("roles", roles);

        if(ttl > 0){
            jwtBuilder.setExpiration(new Date(millis + ttl));
        }

        return jwtBuilder.compact();
    }

    /**
     * 生成jwt token
     * @param id
     * @param subject
     * @param roles
     * @return
     */
    public String createJwt(String id, String subject, String roles, String nickname){
        long millis = System.currentTimeMillis();
        Date date = new Date(millis);
        JwtBuilder jwtBuilder = Jwts.builder()
                .setId(id)
                .setSubject(subject)
                .setIssuedAt(date)
                .signWith(SignatureAlgorithm.HS256, key)
                .claim("roles", roles)
                .claim("nickname", nickname);

        if(ttl > 0){
            jwtBuilder.setExpiration(new Date(millis + ttl));
        }

        return jwtBuilder.compact();
    }

    /**
     * 解析jwt token
     * @param token
     * @return
     */
    public Claims parseJwt(String token){
        return Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(token)
                .getBody();
    }
}
